<?php
/**
 * Archived Projects Page
 * Users can view projects older than 15 days here
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../app/core/db.php';
require_once __DIR__ . '/../app/core/guards.php';

/**
 * Archived Projects Page
 * Users can view projects older than 15 days here
 */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../app/core/config.php';
require_once __DIR__ . '/../app/core/db.php';
require_once __DIR__ . '/../app/core/guards.php';

$pdo = getDbConnection();

// Get user email from session
$user_email = $_SESSION['user_email'] ?? null;

// ===== GET USER_ID FROM EMAIL START =====
$user_id = null;
if ($user_email) {
    try {
        $stmt = $pdo->prepare("SELECT id FROM leads WHERE email = ?");
        $stmt->execute([$user_email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $user_id = $user['id'];
            $_SESSION['user_id'] = $user_id;
        }
    } catch (Exception $e) {
        error_log("Error getting user_id: " . $e->getMessage());
    }
}
// ===== GET USER_ID FROM EMAIL END =====

// Get search parameters
$search = $_GET['search'] ?? '';
$category = $_GET['category'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Build query with saved projects check
$sql = "SELECT p.*, 
        CASE WHEN usp.id IS NOT NULL THEN 1 ELSE 0 END as is_saved
        FROM projects p
        LEFT JOIN user_saved_projects usp 
            ON p.id = usp.project_id AND usp.user_id = ?
        WHERE p.archived = 1";
$params = [$user_id];

if ($search) {
    $sql .= " AND (p.title LIKE ? OR p.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($category && $category !== 'all') {
    $sql .= " AND p.category = ?";
    $params[] = $category;
}

$sql .= " ORDER BY p.archived_at DESC, p.published_at DESC LIMIT ? OFFSET ?";
$params[] = $perPage;
$params[] = $offset;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$archivedProjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ... باقی کد count و categories همونطور که هست بمونه
$pdo = getDbConnection();

// Get search parameters
$search = $_GET['search'] ?? '';
$category = $_GET['category'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Build query
$sql = "SELECT * FROM projects WHERE archived = 1";
$params = [];

if ($search) {
    $sql .= " AND (title LIKE ? OR description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($category && $category !== 'all') {
    $sql .= " AND category = ?";
    $params[] = $category;
}

$sql .= " ORDER BY archived_at DESC, published_at DESC LIMIT ? OFFSET ?";
$params[] = $perPage;
$params[] = $offset;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$archivedProjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get total count for pagination
$countSql = "SELECT COUNT(*) FROM projects WHERE archived = 1";
$countParams = [];
if ($search) {
    $countSql .= " AND (title LIKE ? OR description LIKE ?)";
    $countParams[] = "%$search%";
    $countParams[] = "%$search%";
}
if ($category && $category !== 'all') {
    $countSql .= " AND category = ?";
    $countParams[] = $category;
}

$countStmt = $pdo->prepare($countSql);
$countStmt->execute($countParams);
$totalProjects = $countStmt->fetchColumn();
$totalPages = ceil($totalProjects / $perPage);

// Get categories for filter
$categories = $pdo->query("SELECT DISTINCT category FROM projects WHERE archived = 1 AND category IS NOT NULL ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Archived Projects - ClientRadar</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #f8f9fa;
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* Tabs */
        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .tab {
            padding: 12px 25px;
            border: none;
            background: #e9ecef;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            text-decoration: none;
            color: #495057;
            transition: all 0.3s;
        }
        
        .tab:hover {
            background: #dee2e6;
        }
        
        .tab.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        /* Archive Notice */
        .archive-notice {
            background: #fff3cd;
            border: 2px solid #ffc107;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            text-align: center;
            font-size: 16px;
        }
        
        .archive-notice strong {
            color: #856404;
        }
        
        /* Filters */
        .filters {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .filters form {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .filters input,
        .filters select {
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 15px;
            flex: 1;
            min-width: 200px;
        }
        
        .filters button {
            padding: 12px 30px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 15px;
            font-weight: bold;
        }
        
        .filters button:hover {
            background: #5568d3;
        }
        
        /* Stats */
        .stats {
            background: white;
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        /* Projects Grid */
        .projects-grid {
            display: grid;
            gap: 20px;
        }
        
        .project-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transition: all 0.3s;
            border-right: 4px solid #ffc107;
            opacity: 0.9;
        }
        
        .project-card:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
            opacity: 1;
        }
        
        .project-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }
        
        .project-title {
            font-size: 20px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 5px;
        }
        
        .archive-badge {
            background: #6c757d;
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 13px;
            white-space: nowrap;
        }
        
        .project-meta {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin: 15px 0;
            font-size: 14px;
            color: #6c757d;
        }
        
        .project-meta span {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .project-description {
            color: #495057;
            margin-bottom: 20px;
            line-height: 1.6;
        }
        
        .project-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5568d3;
        }
        
        .btn-secondary {
            background: #10b981;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #059669;
        }
        
        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 30px;
        }
        
        .pagination a {
            padding: 10px 15px;
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            text-decoration: none;
            color: #495057;
            font-weight: bold;
        }
        
        .pagination a:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .pagination a.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .no-results {
            text-align: center;
            padding: 50px;
            background: white;
            border-radius: 10px;
        }
        
        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: 16px;
            padding: 30px;
            max-width: 700px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e5e7eb;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #64748b;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
        }
        
        .spinner {
            border: 4px solid #f3f4f6;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .proposal-text {
            background: #f8f9fa;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 20px;
            font-size: 15px;
            line-height: 1.8;
            color: #1e293b;
            white-space: pre-wrap;
            margin-bottom: 20px;
        }
        
        .copy-btn {
            background: #667eea;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .copy-btn:hover {
            background: #5568d3;
        }
        
        .copy-btn.copied {
            background: #10b981;
        }
        
        .regenerate-btn {
            background: #f59e0b;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            border: none;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .regenerate-btn:hover {
            background: #d97706;
        }
        
        .error-message {
            background: #fef2f2;
            border: 2px solid #fecaca;
            border-radius: 8px;
            padding: 15px;
            color: #991b1b;
            margin-bottom: 15px;
        }
    /* Font Awesome */
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css');

/* Save Button */
.btn-save {
    background: white;
    color: #666;
    border: 2px solid #e0e0e0;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.btn-save:hover {
    border-color: #2196F3;
    color: #2196F3;
}

.btn-save.saved {
    background: #e3f2fd;
    border-color: #2196F3;
    color: #1976d2;
}

.btn-save.saved i {
    color: #2196F3;
}

.btn-save:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
    </style>
</head>
<body>
    <div class="container">
        <!-- Tab Navigation -->
        <div class="tabs">
            <a href="projects_table.php" class="tab">
                🎯 Fresh Projects
            </a>
            <a href="archived_projects.php" class="tab active">
                📦 Archived Projects
            </a>
        </div>
        
        <!-- Archive Notice -->
        <div class="archive-notice">
            ⚠️ <strong>Notice:</strong> These projects are older than 15 days from their publication date 
            and may have already been completed. However, you can still view them and submit proposals.
        </div>
        
        <!-- Filters -->
        <div class="filters">
            <form method="GET" action="">
                <input type="text" 
                       name="search" 
                       placeholder="🔍 Search in title or description..." 
                       value="<?php echo htmlspecialchars($search); ?>">
                
                <select name="category">
                    <option value="all">All Categories</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo htmlspecialchars($cat); ?>" 
                                <?php echo $category === $cat ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                
                <button type="submit">Search</button>
            </form>
        </div>
        
        <!-- Stats -->
        <div class="stats">
            <div>
                <strong>📊 Total:</strong> <?php echo number_format($totalProjects); ?> archived projects
            </div>
            <div>
                <strong>📄 Page:</strong> <?php echo $page; ?> of <?php echo $totalPages; ?>
            </div>
        </div>
        
        <!-- Projects -->
        <?php if (empty($archivedProjects)): ?>
            <div class="no-results">
                <h2>😔 No Projects Found</h2>
                <p>Try different filters or go to fresh projects page.</p>
                <br>
                <a href="projects_table.php" class="btn btn-primary">Go to Fresh Projects</a>
            </div>
        <?php else: ?>
            <div class="projects-grid">
                <?php foreach ($archivedProjects as $project): ?>
                    <div class="project-card">
                        <div class="project-header">
                            <div>
                                <h3 class="project-title">
                                    <?php echo htmlspecialchars($project['title']); ?>
                                </h3>
                            </div>
                            <span class="archive-badge">📦 Archived</span>
                        </div>
                        
                        <div class="project-meta">
                            <?php if ($project['budget']): ?>
                                <span>💰 <?php echo htmlspecialchars($project['budget'] . ' ' . ($project['currency'] ?? '')); ?></span>
                            <?php endif; ?>
                            
                            <?php if ($project['location']): ?>
                                <span>📍 <?php echo htmlspecialchars($project['location']); ?></span>
                            <?php endif; ?>
                            
                            <?php if ($project['category']): ?>
                                <span>🏷️ <?php echo htmlspecialchars($project['category']); ?></span>
                            <?php endif; ?>
                            
                            <span>📅 Published: <?php echo date('M d, Y', strtotime($project['published_at'])); ?></span>
                            
                            <?php if ($project['archived_at']): ?>
                                <span>🗄️ Archived: <?php echo date('M d, Y', strtotime($project['archived_at'])); ?></span>
                            <?php endif; ?>
                        </div>
                        
                        <div class="project-description">
                            <?php 
                            $description = $project['description'] ?? '';
                            echo htmlspecialchars(mb_substr($description, 0, 200)) . (mb_strlen($description) > 200 ? '...' : '');
                            ?>
                        </div>
                        
                        <div class="project-actions">
    <?php if ($user_id): ?>
    <button type="button" class="btn btn-save <?= $project['is_saved'] ? 'saved' : '' ?>" 
            data-project-id="<?= $project['id'] ?>"
            data-saved="<?= $project['is_saved'] ?>">
        <i class="<?= $project['is_saved'] ? 'fas' : 'far' ?> fa-bookmark"></i>
        <?= $project['is_saved'] ? 'Saved' : 'Save' ?>
    </button>
    <?php endif; ?>
    
    <a href="<?php echo htmlspecialchars($project['project_url']); ?>" 
       target="_blank"
       class="btn btn-primary">
        View Project
    </a>
    
    <button type="button" class="btn btn-secondary" onclick="generateProposal(<?php echo $project['id']; ?>, '<?php echo htmlspecialchars(addslashes($project['title'])); ?>')">
        ✨ Generate AI Proposal
    </button>
</div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>">
                            Previous
                        </a>
                    <?php endif; ?>
                    
                    <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>" 
                           class="<?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category); ?>">
                            Next
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- Proposal Modal -->
    <div id="proposalModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>✨ AI Generated Proposal</h2>
                <button class="modal-close" onclick="closeModal()">×</button>
            </div>
            <div id="modalBody"></div>
        </div>
    </div>

    <script>
    function generateProposal(projectId, projectTitle, regenerate = false) {
        const modal = document.getElementById('proposalModal');
        const modalBody = document.getElementById('modalBody');
        
        modal.classList.add('active');
        modalBody.innerHTML = '<div class="loading"><div class="spinner"></div><p>AI is crafting your proposal...</p></div>';
        
        const url = '../ai/generate_test.php?project_id=' + projectId + (regenerate ? '&regenerate=1' : '');
        
        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    modalBody.innerHTML = `
                        <h3 style="margin-bottom: 15px;">For: ${escapeHtml(projectTitle)}</h3>
                        <div class="proposal-text">${escapeHtml(data.proposal)}</div>
                        <div style="display: flex; gap: 10px;">
                            <button class="copy-btn" onclick="copyProposal(this)">📋 Copy to Clipboard</button>
                            <button class="regenerate-btn" onclick="generateProposal(${projectId}, '${escapeHtml(projectTitle).replace(/'/g, "\\'")}', true)">🔄 Regenerate</button>
                        </div>
                    `;
                } else {
                    modalBody.innerHTML = `
                        <div class="error-message"><strong>Error:</strong> ${escapeHtml(data.error)}</div>
                        <button class="copy-btn" onclick="closeModal()">Close</button>
                    `;
                }
            })
            .catch(error => {
                modalBody.innerHTML = `
                    <div class="error-message"><strong>Error:</strong> Failed to generate proposal.</div>
                    <button class="copy-btn" onclick="closeModal()">Close</button>
                `;
            });
    }

    function closeModal() {
        document.getElementById('proposalModal').classList.remove('active');
    }

    function copyProposal(button) {
        const proposalText = document.querySelector('.proposal-text').textContent;
        navigator.clipboard.writeText(proposalText).then(() => {
            button.textContent = '✓ Copied!';
            button.classList.add('copied');
            setTimeout(() => {
                button.textContent = '📋 Copy to Clipboard';
                button.classList.remove('copied');
            }, 2000);
        });
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    document.getElementById('proposalModal').addEventListener('click', function(e) {
        if (e.target === this) closeModal();
    });
    </script>
<script>
// Save/Unsave Functionality
<?php if ($user_id): ?>
document.querySelectorAll('.btn-save').forEach(btn => {
    btn.addEventListener('click', function() {
        const projectId = this.dataset.projectId;
        const isSaved = this.dataset.saved === '1';
        const button = this;
        const icon = this.querySelector('i');
        
        button.disabled = true;
        
        const endpoint = isSaved ? '../app/api/unsave_project.php' : '../app/api/save_project.php';
        
        fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'project_id=' + projectId
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (isSaved) {
                    button.dataset.saved = '0';
                    button.classList.remove('saved');
                    icon.classList.remove('fas');
                    icon.classList.add('far');
                    button.innerHTML = '<i class="far fa-bookmark"></i> Save';
                } else {
                    button.dataset.saved = '1';
                    button.classList.add('saved');
                    icon.classList.remove('far');
                    icon.classList.add('fas');
                    button.innerHTML = '<i class="fas fa-bookmark"></i> Saved';
                }
            } else {
                alert(data.message || 'An error occurred');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to update project');
        })
        .finally(() => {
            button.disabled = false;
        });
    });
});
<?php endif; ?>
</script>
</body>
</html>